<?php
/**
 * @copyright Arthur Beer
 * @package image
 *
 * @copyright TinyWEB CMS
 * @link http://tinywebcms.ru
 * @link http://cms.vingrad.ru
 * @version SVN: $Id$ 
 */
 
/**
 * ImageRemoteSaver
 */
class ImageRemoteSaver extends Image 
{
    protected $path;
    protected $root;
    
    public function __construct($path, $root, ImageRemoteLinksGrabber $ImageRemoteTextGrabber)
    {
        $this->path = rtrim($path, '/') . date('/Y/m/d');
        $this->root = $root;
        
        $ImagesModel = new ImagesModel(true);
        
        foreach ($ImageRemoteTextGrabber as $image) {
            $ImagesModel->startTransaction();
            
            try {
                $id = $ImagesModel->create(mb_substr($image, -3));
                $FilesSingleRemoteUploader = $this->upload($image, $id);
                $ImageRemoteTextGrabber->replace($image, '/' . ltrim(str_replace($this->root, '', $FilesSingleRemoteUploader->getSavePath()), '/'));
            } catch (Exception $e) {
                if($FilesSingleRemoteUploader instanceof FilesSingleRemoteUploader) {
                    unlink($FilesSingleRemoteUploader->getSavePath());
                }
                
                throw new ModelRollbackException($e, $ImagesModel);
            }
            
            $ImagesModel->commit();
        }
    }
    
    /**
     * Upload file
     *
     * @param string $url
     * @return FilesSingleRemoteUploader
     */
    public function upload($url, $name)
    {
        $FilesSingleRemoteUploader = new FilesSingleRemoteUploader($url, $this->path, new FilesTypeImages());
        $FilesSingleRemoteUploader->rename($name . '.%s');
        $FilesSingleRemoteUploader->exec();
        return $FilesSingleRemoteUploader;
    }
}

/**
 * Tab: 4 spaces
 * Encoding: utf-8
 */
?>